import { useUserStoreWithOut } from "./store/modules/user"
import { usePermissionStoreWithOut } from "./store/modules/permission"
import router from "@/router"
import { ROUTER_WHITE_LIST } from "../constants"
// import { menuApi } from "./api/menu"
import { useTitle } from "./hooks/web/useTitle"
import { userApi } from "./api/admin/user"
import { ElMessage } from "element-plus"
// import { deepClone } from "./utils"

router.beforeEach(async (to, from, next) => {

  const userStore = useUserStoreWithOut()
  // console.log(to);
  // console.log(from);

  if (userStore?.getUserInfo) {
    if (to.path === "/login") {
      next("/")
    } else {

      if (ROUTER_WHITE_LIST.indexOf(to.path) !== -1) {
        next()
      }

      const permissionStore = usePermissionStoreWithOut()

      const userRoles = userStore.getUserRoles
      if (userRoles.length === 0) {
        const res = await userApi.getUserRolesApi()
        if (res.code == 200) {
          if (res.data.length === 0) {
            console.error('当前用户没有角色，请先联系管理员分配角色')
            ElMessage.info("当前用户没有角色，请先联系管理员分配角色")
            next("/login")
            return
          }
          userStore.setUserRoles(res.data)
        } else {
          ElMessage.info("获取用户角色失败")
        }
        // state.userRoles = res.data
      }

      // 如果已经添加动态路由，直接进入
      if (permissionStore.getIsAddRoutes && userStore.roleRouters) {
        // console.log(permissionStore.getAddRoutes);
        if (to.path === "/") {
          const defaultRoutePath = permissionStore.getDefaultRoutePath
          next(defaultRoutePath)
          return
        }

        next()
        return
      } else {
        try {
          // 获取动态路由
          // const roleRoutesRes: any = await menuApi.getRoutesMenuTreeApi()
          const roleRoutesRes: any = await userApi.getUserMenuApi()
          // console.log(roleRoutesRes);
          userStore.setRoleRouters(roleRoutesRes)

          const roleRouters = userStore.roleRouters
          // console.log(roleRouters);

          await permissionStore.generateRouter(roleRouters)
          // console.log(permissionStore.getAddRoutes);

          permissionStore.getAddRoutes.forEach((route: any) => {
            router.addRoute(route)
          })

          // console.log("to",to);
          // console.log("from",from);

          const redirectPath = from.query.redirect || to.path
          const redirect = decodeURIComponent(redirectPath as string)
          const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect }
          permissionStore.setIsAddRoutes(true)
          next(nextData)
        } catch {
          // userStore.logout()
          next({ path: "/error" })
        }
      }
    }
  } else {
    ROUTER_WHITE_LIST.indexOf(to.path) !== -1 ? next() : next(`/login?redirect=${to.path}`)
  }
})


router.afterEach((to) => {
  const title = to?.meta?.title
  useTitle((title as string))

})